//
//  JXLOAuthViewController.swift
//  MicroBlog
//
//  Created by 贾晓磊 on 16/9/22.
//  Copyright © 2016年 贾晓磊. All rights reserved.
//
//  第三方登录视图控制器
//  新浪开发平台提供的APPKey
let WeiboAppKey = "603689761"
//  授权回调页
let WeiboRedirect_Uri = "http://www.autohome.com.cn"
//  AppSecret
let WeiboAppSecret = "b9b1c1557123012b00cb0a0473ac1683"
import UIKit
import SVProgressHUD

class JXLOAuthViewController: UIViewController {

    private lazy var webView: UIWebView = UIWebView()
    
    //MARK: 方法＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝
    //重写这个方法，把webView作为控制器的视图
    override func loadView() {
        view = webView
        
        
        //解决底部webView黑条
        //改成透明，解决黑条问题
        webView.isOpaque = false
        
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        requestLogin()
        setupNavUI()
    }
    
    //添加导航栏登陆与注册按钮
    private func setupNavUI() -> Void {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imageName: nil, target: self, action: #selector(cancelAction))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", imageName: nil, target: self, action: #selector(autoFillupAction))
        title = "微博"
    }

   //请求第三方数据
    private func requestLogin() {
        //准备url
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"
        
        let urlRequest = URLRequest(url: URL(string: url)!)
        
        webView.loadRequest(urlRequest)
    }
        
        //点击左侧取消按钮方法
       @objc private func cancelAction() {
        
        SVProgressHUD.dismiss()
        
        dismiss(animated: true, completion: nil)
        }
    
    //点击左侧取消按钮方法
    @objc private func autoFillupAction() {
        print("自动填充")
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = 'jiaxiaolei1987@163.com';document.getElementById('passwd').value = 'P@ssw0rd'")
    }

   
}


// MARK: 实现webView的代理方法

extension JXLOAuthViewController: UIWebViewDelegate {
   //开始加载数据
    func webViewDidStartLoad(_ webView: UIWebView) {
        //开始加载数据，数据显示之前，转动小菊花
        SVProgressHUD.show()
    }
    //完成加载数据
    func webViewDidFinishLoad(_ webView: UIWebView) {
        //完成加载数据，数据显示，小菊花消失
        SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        //完成加载数据，数据显示，小菊花消失
        SVProgressHUD.dismiss()
    }
    //将要开始加载数据
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.url else {
            
            print("url 为 nil")
            
            return false
        }
        //如果地址中以WeiboRedirect_Uri开头就进入判断，其他的正常请求
        if url.absoluteString.hasPrefix(WeiboRedirect_Uri) {
            
        //query是一个参数，代表地址里边？问号之后的code=...那段字符串
            if let query = url.query , query.hasPrefix("code=") {
                
                //  根据光标的结束位置获取子串
                let code = query.substring(from: "code=".endIndex)
                
                print(code)
                 //  通过code获取accesstoken
               JXLUserAccountViewModel.sharedUserAccountViewModel.requestAccessToken(code: code, callBack: { (isSuccessful) in
                
                if isSuccessful {
                    print("登录成功")
                   //要等要dismiss成功再切换根视图
                    self.dismiss(animated: true, completion: {
                        
                        //登录成功，发送通知，切换到欢迎页面
                        NotificationCenter.default.post(name:Notification.Name(SwitchRootVCNotification), object: self)
                    })
                    
                }
               })
                
                
            } else {
                dismiss(animated: true, completion: nil)
            }
        } else {
            return true
        }
        return false
    }
}

